<template>
  <div class="space-y-6">
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">SOP签核追踪</h2>
      <button @click="showAddModal = true" class="btn btn-primary">
        <i class="fas fa-plus mr-2"></i>新增SOP
      </button>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
      <div class="card bg-blue-50">
        <div class="text-center">
          <div class="text-2xl font-bold text-blue-600">{{ stats.total }}</div>
          <div class="text-sm text-blue-800">总SOP数</div>
        </div>
      </div>
      <div class="card bg-yellow-50">
        <div class="text-center">
          <div class="text-2xl font-bold text-yellow-600">{{ stats.pending }}</div>
          <div class="text-sm text-yellow-800">待签核</div>
        </div>
      </div>
      <div class="card bg-green-50">
        <div class="text-center">
          <div class="text-2xl font-bold text-green-600">{{ stats.approved }}</div>
          <div class="text-sm text-green-800">已签核</div>
        </div>
      </div>
      <div class="card bg-red-50">
        <div class="text-center">
          <div class="text-2xl font-bold text-red-600">{{ stats.rejected }}</div>
          <div class="text-sm text-red-800">已拒绝</div>
        </div>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="card">
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">机型</label>
          <input v-model="filters.model" type="text" class="form-input" placeholder="搜索机型">
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
          <select v-model="filters.status" class="form-input">
            <option value="">全部</option>
            <option value="pending">待签核</option>
            <option value="approved">已签核</option>
            <option value="rejected">已拒绝</option>
          </select>
        </div>
        <div class="flex items-end">
          <button @click="clearFilters" class="btn btn-secondary mr-2">清除</button>
          <button @click="searchSOPs" class="btn btn-primary">搜索</button>
        </div>
      </div>
    </div>

    <!-- SOP列表 -->
    <div class="card">
      <div class="overflow-x-auto">
        <table class="table">
          <thead>
            <tr>
              <th>序号</th>
              <th>机型</th>
              <th>状态</th>
              <th>提交时间</th>
              <th>签核时间</th>
              <th>备注</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="sop in filteredSOPs" :key="sop.id">
              <td>{{ sop.serial }}</td>
              <td>{{ sop.model }}</td>
              <td>
                <span :class="getStatusClass(sop.status)">
                  {{ getStatusText(sop.status) }}
                </span>
              </td>
              <td>{{ sop.submitTime }}</td>
              <td>{{ sop.approvalTime || '-' }}</td>
              <td>{{ sop.notes || '-' }}</td>
              <td>
                <button @click="editSOP(sop)" class="text-blue-600 hover:text-blue-900 mr-2">
                  <i class="fas fa-edit"></i>
                </button>
                <button @click="deleteSOP(sop)" class="text-red-600 hover:text-red-900">
                  <i class="fas fa-trash"></i>
                </button>
              </td>
            </tr>
            <tr v-if="filteredSOPs.length === 0">
              <td colspan="7" class="text-center text-gray-500 py-8">暂无数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增/编辑模态框 -->
    <div v-if="showAddModal || showEditModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
      <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <h3 class="text-lg font-medium mb-4">{{ isEdit ? '编辑SOP' : '新增SOP' }}</h3>
        <form @submit.prevent="saveSOP">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">序号</label>
            <input v-model.number="form.serial" type="number" class="form-input" required min="1">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">机型</label>
            <input v-model="form.model" type="text" class="form-input" required>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">状态</label>
            <select v-model="form.status" class="form-input">
              <option value="pending">待签核</option>
              <option value="approved">已签核</option>
              <option value="rejected">已拒绝</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">提交时间</label>
            <input v-model="form.submitTime" type="date" class="form-input" required>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">签核时间</label>
            <input v-model="form.approvalTime" type="date" class="form-input">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 mb-2">备注</label>
            <textarea v-model="form.notes" class="form-input" rows="3"></textarea>
          </div>
          <div class="flex justify-end space-x-2">
            <button type="button" @click="closeModal" class="btn btn-secondary">取消</button>
            <button type="submit" class="btn btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useDataStore } from '../stores'
import { showAlert, confirmDialog } from '../utils/notifications'
import type { SOPApproval } from '../types'

const store = useDataStore()
const sopApprovals = computed(() => store.sopApprovals)

const showAddModal = ref(false)
const showEditModal = ref(false)
const isEdit = ref(false)
const form = ref<SOPApproval>({
  serial: 0,
  model: '',
  status: 'pending',
  submitTime: '',
  approvalTime: '',
  notes: ''
})

const filters = ref({
  model: '',
  status: ''
})

const stats = computed(() => {
  const total = sopApprovals.value.length
  const pending = sopApprovals.value.filter(s => s.status === 'pending').length
  const approved = sopApprovals.value.filter(s => s.status === 'approved').length
  const rejected = sopApprovals.value.filter(s => s.status === 'rejected').length
  return { total, pending, approved, rejected }
})

const filteredSOPs = computed(() => {
  return sopApprovals.value.filter(sop => {
    return (!filters.value.model || sop.model.includes(filters.value.model)) &&
           (!filters.value.status || sop.status === filters.value.status)
  })
})

function getStatusClass(status: string) {
  const classes = {
    pending: 'bg-yellow-100 text-yellow-800',
    approved: 'bg-green-100 text-green-800',
    rejected: 'bg-red-100 text-red-800'
  }
  return classes[status as keyof typeof classes] || 'bg-gray-100 text-gray-800'
}

function getStatusText(status: string) {
  const texts = {
    pending: '待签核',
    approved: '已签核',
    rejected: '已拒绝'
  }
  return texts[status as keyof typeof texts] || '未知'
}

function editSOP(sop: SOPApproval) {
  form.value = { ...sop }
  isEdit.value = true
  showEditModal.value = true
}

async function deleteSOP(sop: SOPApproval) {
  const confirmed = await confirmDialog(`确定要删除SOP ${sop.model} 吗？`)
  if (confirmed) {
    const index = store.sopApprovals.findIndex(s => s.id === sop.id)
    if (index > -1) {
      store.sopApprovals.splice(index, 1)
      showAlert('删除成功', 'success')
    }
  }
}

function closeModal() {
  showAddModal.value = false
  showEditModal.value = false
  isEdit.value = false
  form.value = {
    serial: 0,
    model: '',
    status: 'pending',
    submitTime: '',
    approvalTime: '',
    notes: ''
  }
}

function saveSOP() {
  if (isEdit.value) {
    const index = store.sopApprovals.findIndex(s => s.id === form.value.id)
    if (index > -1) {
      store.sopApprovals[index] = { ...form.value }
      showAlert('更新成功', 'success')
    }
  } else {
    store.sopApprovals.push({
      ...form.value,
      id: Date.now().toString()
    })
    showAlert('添加成功', 'success')
  }
  closeModal()
}

function clearFilters() {
  filters.value = {
    model: '',
    status: ''
  }
}

function searchSOPs() {
  // 搜索逻辑已在 computed 中实现
}
</script>
